#表单通用操作

config = require('../config')
db = require('../config').mongoose.db
resErr = require('./util').resErr
_ = require('underscore')
ObjectId = require('mongoose').Types.ObjectId

#查询所有
exports.form_common_listall = (req,res)->
  collection = req.param('collection')
  return resErr res,'collection不得为空！' if !collection
  params = {}
  sorts = {}
  fields = {}
  cursor = db.collection(collection).find(params)
  cursor.sort(sorts)
  cursor.toArray (err,docs)->
    if err
      resErr res,err
    else
      res.json docs



#分页查询
exports.form_common_listpage = (req,res)->
  collection = req.param('collection')
  return resErr res,'collection不得为空！' if !collection

  params = {}
  db.collection('forms').findOne {form_code:collection},(err,document)->
    return resErr res,err if err
    if !document
      return resErr res,'无法找到collection，请先配置！'

    if document.search_fields && document.search_fields.length>0
      # 默认支持多级联动查询
      for field in document.fields
        if !field
          continue
        else
          if field.xtype == "cascade"
            params[field.name] = req.param(field.name) if field.name && req.param(field.name)
            params[field.cascade_field2] = req.param(field.cascade_field2) if field.cascade_field2 && req.param(field.cascade_field2) 
            params[field.cascade_field3] = req.param(field.cascade_field3) if field.cascade_field3 && req.param(field.cascade_field3) 
      for field in document.search_fields
        if !field
          continue
        else
          if field.is_like
            params[field.name] = {'$regex':req.param(field.name)} unless !req.param(field.name)
          else
            params[field.name] = req.param(field.name) unless !req.param(field.name)

    #排序
    sorts = {}
    sort = req.param('sort')
    dir = req.param('dir')
    if dir && sort
      dir = if dir.toUpperCase() == 'ASC' then 1 else -1
      sorts[sort] = dir

    fields = {}
    pageSize = parseInt(req.param("pageSize") || req.param("limit")  || "10")
    pageNum = parseInt(req.param("pageNum") || req.param("page") || "1")
    limit = pageSize
    skip = (pageNum - 1) * limit
    cursor = db.collection(collection).find(params)
    cursor.sort(sorts)
    cursor.limit(parseInt(limit)).skip(parseInt(skip))
    cursor.toArray (err,docs)->
      if err
        resErr res,err
      else
        db.collection(collection).count params,(err,count) ->
          if err
            resErr res,err
          else
            results = {}
            results.pageSize = limit
            results.pageNum = pageNum
            results.pageCount = if(count % limit == 0 ) then count / limit else parseInt(count / limit) + 1
            results.count = count
            results.data = docs
            res.json results



#新增
exports.form_common_add = (req,res)->
  collection = req.param('collection')
  return resErr res,'collection不得为空！' if !collection
  options = {w:1}
  db.collection('forms').findOne {form_code:collection},(err,document)->
    return resErr res,err if err
    if !document
      return resErr res,'无法找到collection，请先配置！'
    result = {}
    result['image_file_id'] = req.param('image_file_id')
    for field in document.fields
      return resErr res,field.name + '不得为空' if !field.allow_blank && !req.param(field.name)
      _tmp = req.param(field.name)
      if field.xtype == "cascade"
        console.log "cascade****"
        result[field.name] = req.param(field.name) if req.param(field.name)
        result[field.cascade_field2] = req.param(field.cascade_field2) if field.cascade_field2 && req.param(field.cascade_field2) 
        result[field.cascade_field3] = req.param(field.cascade_field3) if field.cascade_field3 && req.param(field.cascade_field3)
      else if _tmp
        if field.data_type == 'Integers'
          result[field.name] = parseInt(_tmp)  if !isNaN(parseInt(_tmp))
        else if field.data_type == 'Float'
          result[field.name] = parseFloat(_tmp)  if !isNaN(parseFloat(_tmp))
        else if field.data_type == 'Date'
          result[field.name] = new Date(_tmp)  if !isNaN(Number(new Date(_tmp)))
        else
          result[field.name] = _tmp
        return resErr res,'字段' + field.name + '类型转换失败，请检查！' if _.isNull(result[field.name])
    if !_.isEmpty(result)
      console.log result.image_file_id
      result['updated_at'] = new Date
      db.collection(collection).insert result,options,(err,records)->
        return resErr res,err if err
        console.log records
        res.json({flag:'success'})
    else
      resErr res,'未插入任何数据！'

#根据id查询明细
exports.form_common_detail = (req,res)->
  collection = req.param('collection')
  return resErr res,'collection不得为空！' if !collection
  _id = req.param('_id')
  return resErr res,'_id不得为空！' if !collection

  db.collection(collection).findOne ObjectId(_id),(err,result)->
    return resErr res,err if err
    res.json result

#根据id修改
exports.form_common_edit = (req,res)->
  collection = req.param('collection')
  return resErr res,'collection不得为空！' if !collection
  _id = req.param('_id')
  return resErr res,'_id不得为空！' if !collection

  result = {}
  options = {}
  sorts = {'_id','asc'}

  db.collection('forms').findOne {form_code:collection},(err,doc)->
    return resErr res,err if err
    result['image_file_id'] = req.param('image_file_id') if req.param('image_file_id')
    for field in doc.fields
      return resErr res,field.name + '不得为空' if !field.allow_blank && !req.param(field.name)
      _tmp = req.param(field.name)
      console.log "****************"
      console.log field
      if field.xtype == "cascade"
        console.log "cascade****"
        result[field.name] = req.param(field.name) if req.param(field.name)
        result[field.cascade_field2] = req.param(field.cascade_field2) if field.cascade_field2 && req.param(field.cascade_field2) 
        result[field.cascade_field3] = req.param(field.cascade_field3) if field.cascade_field3 && req.param(field.cascade_field3)
      else if _tmp
        if field.data_type == 'Integers'
          result[field.name] = parseInt(_tmp)  if !isNaN(parseInt(_tmp))
        else if field.data_type == 'Float'
          result[field.name] = parseFloat(_tmp)  if !isNaN(parseFloat(_tmp))
        else if field.data_type == 'Date'
          result[field.name] = new Date(_tmp)  if !isNaN(Number(new Date(_tmp)))
        else
          result[field.name] = _tmp
        return resErr res,'字段' + field.name + '类型转换失败，请检查！' if !result[field.name]

    if !_.isEmpty(result)
      result['updated_at'] = new Date
      db.collection(collection).update {_id: ObjectId(_id)}, {$set: result}, {w:1}, (err) ->
        return resErr res,err if err
        res.json({flag:'success'})
    else
      resErr res,'未插入任何数据！'

      
#根据id删除
exports.form_common_del = (req,res)->
  collection = req.param('collection')
  return resErr res,'collection不得为空！' if !collection
  _id = req.param('_id')
  return resErr res,'_id不得为空！' if !_id
  db.collection(collection).remove {_id:ObjectId(_id)},(err) ->
    return resErr res,err if err
    res.json({flag:'success'})






